import time
import functools
import numpy as np

def timer(repeats=10, warm_up=3):
    """
    函数执行时间统计装饰器
    :param repeats: 正式计时运行次数 (默认10次)
    :param warm_up: 预热次数 (默认3次)
    """
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 预热阶段 (不记录时间)
            for _ in range(warm_up):
                func(*args, **kwargs)
            
            # 正式计时阶段
            timings = []
            result = None
            for _ in range(repeats):
                start_time = time.perf_counter()
                result = func(*args, **kwargs)  # 保留最后一次结果
                end_time = time.perf_counter()
                timings.append(end_time - start_time)
            
            # 计算统计指标
            avg_time = np.mean(timings) * 1000  # 转毫秒
            min_time = np.min(timings) * 1000
            max_time = np.max(timings) * 1000
            std_dev = np.std(timings) * 1000
            
            # 打印统计结果
            print(f"\n=== 函数 {func.__name__} 性能分析 ===")
            print(f"预热次数: {warm_up} | 采样次数: {repeats}")
            print(f"平均耗时: {avg_time:.4f} ms")
            print(f"最快耗时: {min_time:.4f} ms | 最慢耗时: {max_time:.4f} ms")
            print(f"时间波动: ±{std_dev:.4f} ms")
            
            return result  # 返回原始函数结果
        
        return wrapper
    return decorator

# 使用示例
if __name__ == "__main__":
    @timer(repeats=5, warm_up=2)
    def fibonacci(n):
        """计算斐波那契数列"""
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a
    
    # 执行函数并自动打印计时结果
    print("计算结果:", fibonacci(10000))